package com.it.config;

import cn.hutool.json.JSONUtil;
import com.it.vo.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * TODO
 *
 * @author: Coke
 * @DateTime: 2023/11/19/22:17
 **/
@Slf4j
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    // 处理访问被拒绝的逻辑
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
          throws IOException, ServletException {
        // 记录权限不足的日志信息
        log.info("权限不足！！");
        
        // 设置响应的内容类型为JSON，使用UTF-8字符集
        response.setContentType("application/json;charset=UTF-8");
        
        // 设置响应状态为403 Forbidden
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        
        // 获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        
        // 构建错误响应，包含访问被拒绝的消息
        Response<?> error = Response.error(accessDeniedException.getMessage());
        
        // 将错误响应转换为JSON字符串，并写入输出流中
        outputStream.write(JSONUtil.toJsonStr(error).getBytes(StandardCharsets.UTF_8));
        
        // 刷新输出流
        outputStream.flush();
        
        // 关闭输出流
        outputStream.close();
    }
}
